<template>
  <!-- 预备投资项目库  -->
    <div class="interestCalculationDetailsPage">
        <div class="search-wrap d-flex flex-wrap">
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>项目名称</label>
                <el-input v-model="form.projectName" class="m-l5" placeholder="请输入项目名称"></el-input>
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>创建时间</label>
                <el-date-picker
                    class="m-l10"
                    v-model="form.valueTime"
                    @change="createTimeChange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="large"
                />
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>项目类型</label>
                <el-select v-model="form.projectTypeId" class="m-l10">
                    <el-option v-for="(item,index) in state.projectType" :key="index" :label="item.enumName" :value="item.enumId"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>项目负责部门</label>
                <el-select
                    v-model="form.departmentId"
                    class="m-l10"
                    @change="departmentChange"
                >
                    <el-option v-for="(item,index) in state.allDepartmentList" :key="index" :label="item.departmentName" :value="item.departmentId"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>发起人</label>
                <el-select
                    v-model="form.responsibleUserId"
                    class="m-l10"
                >
                    <el-option v-for="(item,index) in state.departmentPersonList" :key="index" :label="item.userName" :value="item.userId"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>方案状态</label>
                <el-select
                    v-model="form.planStatus"
                    class="m-l10"
                >
                    <el-option  label="审批中" value="1"></el-option>
                    <el-option  label="已通过" value="2"></el-option>
                    <el-option  label="已驳回" value="3"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20 m-b10">
                <label>立项议题状态</label>
                <el-select
                    v-model="form.subjectMeetingStatus"
                    class="m-l10"
                >
                    <el-option  label="未发起" value="0"></el-option>
                    <el-option  label="审批中" value="1"></el-option>
                    <el-option  label="已通过" value="2"></el-option>
                    <el-option  label="已驳回" value="3"></el-option>
                </el-select>
            </div>

            <div class="search-buttons m-l50 d-flex a-center m-b10">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="请选择需要删除的数据!"
                    placement="top-start"
                    :disabled="state.selectedList.length>0"
                >
                    <el-button
                        color="#F12527"
                        style="color: #FFFFFF;"
                        @click="batchDelete"
                    >批量删除</el-button>
                </el-tooltip>
                <el-button
                    style="color:#FC7018;background: #FFFFFF;"
                    @click="addHandle"
                >
                    <svg-icon icon-class="add-icon-1" class="icon-export m-r5"></svg-icon>
                    新增
                </el-button>
                <el-button
                    style="color:#FC7018;background: #FFFFFF;"
                    @click="onExport"
                >
                    <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>
                    一键导出
                </el-button>
                <el-divider class="m-l50 m-r50" direction="vertical" />
                <el-button
                    color="#fc702b"
                    style="color:#fff;"
                    @click.prevent="onQuery"
                >查询</el-button>
                <el-button
                    color="#f0f0f0"
                    style="color: #000000"
                    @click.prevent="onReset"
                >重置</el-button>
            </div>
        </div>
        <public-table
                ref="publicTableRef"
                index
                selection
                :indexWidth="'100'"
                :page="page"
                :tableData="tableData"
                :tableOption.sync="tableOption"
                @page-change="onPageChange"
                @handleSelectionChange="handleSelectionChange"
        >
            <template #buttons="scope">
                <el-button
                    class="m-b10"
                    color="#D4AE85"
                    style="color:#FFFFFF;"
                    @click="toProgrammeManagement(scope.row)"
                >
                    方案管理
                </el-button>
                <el-button
                    class="m-b10"
                    color="#7D7D9A"
                    style="color:#FFFFFF;"
                    @click="openProjectPhase(scope.row)"
                >
                    项目阶段
                </el-button>
                <el-button
                    class="m-b10"
                    color="#D4AE85"
                    style="color:#FFFFFF;"
                    @click="openProjectProposal(scope.row,'submit')"
                >
                    立案议题
                </el-button>
                <el-button
                    class="m-b10"
                    color="#D4AE85"
                    style="color:#FFFFFF;"
                    @click="openProjectApprovalForm(scope.row,'submit')"
                >
                    立项审批
                </el-button>
                <el-button
                        class="m-b10"
                        color="#FFF8F6"
                        style="color:#FC7018;border-color: #FC7018;"
                        @click="editHandle(scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                        class="m-b10"
                        color="#FC7018"
                        style="color:#FFFFFF;"
                        @click="queryHandle(scope.row)"
                >
                    查看
                </el-button>
                <svg-icon
                        icon-class="delete-icon"
                        class="delete-icon m-l10 m-b10"
                        @click="deleteHandle(scope.row)"
                ></svg-icon>
            </template>
            <template #subjectMeetingStatus="scope">
                <span v-if="scope.row.subjectMeetingStatus!==2">{{['未发起','审批中','已通过','已驳回'][scope.row.subjectMeetingStatus]}}</span>
                <span
                    style="color: #fc7037;cursor: pointer;"
                    v-if="scope.row.subjectMeetingStatus===2"
                    @click="openProjectProposal(scope.row,'query')"
                >已通过</span>
            </template>
            <template #projectApprovalStatus="scope">
                <span v-if="scope.row.projectApprovalStatus!==2">{{['未发起','审批中','已通过','已驳回'][scope.row.projectApprovalStatus]}}</span>
                <span
                    style="color: #fc7037;cursor: pointer;"
                    v-if="scope.row.projectApprovalStatus===2"
                    @click="openProjectApprovalForm(scope.row,'query')"
                >已通过</span>
            </template>
        </public-table>
    </div>

    <add-investment-projects
        ref="addInvestmentProjectsRef"
        :title="state.title"
        v-model:visible="addInvestmentProjectsVisible"
        @on-success="onSuccess"
        @departmentChange="departmentChange"
    ></add-investment-projects>

    <project-phase-popup ref="projectPhasePopupRef"/>
    <project-approval-form
        ref="projectApprovalFormRef"
        @on-success="onSuccess"
    />
    <project-proposal
        ref="projectProposalRef"
        @on-success="onSuccess"
    />
</template>

<script setup>
import {onMounted, reactive, ref, provide} from "vue";
import {
    ElDivider,
    ElDatePicker, ElLoading, ElMessage, ElMessageBox,
    ElTooltip
} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";
import {tableCommonFun} from "@/hooks/tableCommon";
import {physicalCultureApi} from "@/api/businessFinance";
import {exportExcelFile} from "@/common/utils/GlobalUtils";
import {useRouter} from "vue-router";
import {otherApi, projectSetApi, reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {department} from "@/api/project";
import AddInvestmentProjects from "./components/addInvestmentProjects";
import ProjectPhasePopup from "./programmeManagement/components/projectPhasePopup";
import ProjectApprovalForm from "./components/projectApprovalForm";
import ProjectProposal from "./components/projectProposal";

const interfaceConfig = reactive({
    fileName:'investment',
    apiPath:'reserveInvestmentProjectLibraryApi.getPage',
});
const exportConfig = reactive({
    fileName:'investment',
    apiPath:'projectSetApi.exportProjectSet',
    tableName:'项目集表'
});

/**
 * 默认参数
 * @type {UnwrapNestedRefs<{prepareStatus: number}>}
 */
const defaultParameters = reactive({
    prepareStatus:-1
});

const {
    form,
    page,
    tableOption,
    tableData,
    onQuery,
    onReset,
    onPageChange,
    getData,
    onExport
}  = tableCommonFun(interfaceConfig,exportConfig,defaultParameters);

form.value = {
    projectName:'',
    startTime:'',
    endTime:'',
    projectTypeId:'',
    responsibleUserId:'',
    planStatus:'',
    subjectMeetingStatus:'',
    departmentId:'',
    prepareStatus:-1,
    valueTime:'',
}

tableOption.value = [
    { label: "项目名称", prop: "projectName" },
    { label: "项目类型", prop: "projectTypeName" },
    { label: "行业类型", prop: "industryTypeName" },
    { label: "项目总投（万）", prop: "projectAmount",width:150 },
    { label: "发起人", prop: "responsibleUserName" },
    { label: "创建时间", prop: "createTime" },
    { label: "创建人", prop: "createUserName" },
    { label: "方案状态", prop: "planStatus",formatter:(val,row)=>{
        return ['未发起','审批中','已通过','已驳回'][val] || '-';
    } },
    { label: "立项议题状态", prop: "subjectMeetingStatus",width:150,slot:true,formatter:(val,row)=>{
            return ['未发起','审批中','已通过','已驳回'][val] || '-';
    } },
    { label: "立项审批状态", prop: "projectApprovalStatus",width:150,slot:true,formatter:(val,row)=>{
            return ['未发起','审批中','已通过','已驳回'][val] || '-';
        } },

    {   label: '操作',
        slot: true,
        width: 400,
        overHidden:false,
        slotName: 'buttons',
        fixed: "right"
    },
];

const state = reactive({
    projectType:[],
    industryList:[],
    partnerList:[],
    companyList:[],
    selectedList:[],
    allDepartmentList:[],
    departmentPersonList:[],
    projectSetList:[],
    row:null,
    title:'新增',
});

provide('state', state);

/**
 * 导入按钮
 */
const onImport = () => {
    visible.value = true;
}

/**
 * 模版导出按钮
 */
const onTemplateExport = () => {
    physicalCultureApi.bfFinanceOtherParkingLotTemplate().then(res=>{
        if(res){
            exportExcelFile(res,'停车场其他业务账单模版');
        }else{
            ElMessage.error('导出失败!');
        }
    });
}

/**
 * 上次文件方法
 * @param file
 */
const uploadFile = (file) => {
    const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(0, 0, 0, 0.7)",
    });
    let uploadFile = new FormData();
    uploadFile.append("file", file.file);
    physicalCultureApi.importExcelBfFinanceOtherParkingLot(uploadFile).then(res=>{
        if (res.code == 200) {
            loading.close();
            ElMessage.success("上传成功!");
            visible.value = false;
            getData({
                pageNum:1,
                pageSize:10,
                param:{}
            });
        }
    });
}

const router = useRouter();
/**
 * 添加或者编辑项目集
 */
const addAndEditHandle = (type,row) => {
    router.push({path:`/investmentProjectManagement/preparatoryProject/programManagementAddAndEdit/${type}/${row.projectSetId || "-"}`});
}

/**
 * 获取下拉框
 */
const getListEnum = (type) => {
    otherApi.getListEnum({type: type}).then(res=>{
        const {code,data} = res;
        if(code == 200){
            type==1?state.projectType = data:state.industryList = data;
        }
    });
}

/**
 * 获取所有部门
 */
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data, msg } = res;
        if (code == 200) {
            state.allDepartmentList = data;
        }
    });
};

/**
 * 根据部门id查负责人
 * @param responsibleDepartmentId
 */
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
    department.getLeaderByDepartmentId(responsibleDepartmentId).then((res) => {
        const { code, data, msg } = res;
        if (code == 200) {
            state.departmentPersonList = data;
        }
    });
};

/**
 * 部门选中
 * @param e
 */
const departmentChange = (e) => {
    getLeaderByDepartmentId(e);
}

/**
 * 创建时间
 * @param e
 */
const createTimeChange = (e) => {
    if (e && (e instanceof Array) && e.length!==0){
        form.value.startTime = e[0];
        form.value.endTime = e[1];
    }
    if(!e || (e instanceof Array && e.length ===0)){
        form.value.startTime = '';
        form.value.endTime = '';
    }
}

/**
 * 新增
 */
const addInvestmentProjectsVisible = ref(false);
const addInvestmentProjectsRef = ref(null);
const addHandle = () => {
    state.title = '新增';
    addInvestmentProjectsVisible.value = true;
    addInvestmentProjectsRef.value.reset('add');
}

/**
 * 合作方
 */
const getAllPartner = () => {
    reserveInvestmentProjectLibraryApi.getAllPartner().then(res=>{
        const {code,data} = res;
        if(code == 200){
            state.partnerList = data;
        }
    });
}

/**
 * 实施主体
 */
const getCompanyList = () => {
    otherApi.getCompanyList({}).then(res=>{
        const {code,data} = res;
        if(code == 200){
            state.companyList = data;
        }
    });
}

/**
 * 查询项目集
 * @param params
 */
const getProjectSetPage = (params) => {
    projectSetApi.getProjectSetPage(params).then(res=>{
        if(res.code == 200){
            state.projectSetList = res.data.content;
        }
    });
}

const onSuccess = () => {
  onQuery();
}

const editHandle = (row) => {
    state.row = row;
    state.title = '编辑';
    state.projectId = row.projectId;
    addInvestmentProjectsVisible.value = true;
    addInvestmentProjectsRef.value.reset('edit');
}

/**
 * 表格多选
 * @param e
 */
const handleSelectionChange = (e) => {
  state.selectedList = e;
}

/**
 * 删除
 */
const deleteList = (param,callback) => {
    reserveInvestmentProjectLibraryApi.deleteList(param).then(res=>{
        if(res.code == 200){
            if(callback)callback();
        }
    });
}

/**
 * 批量删除
 */
const batchDelete = () => {
    if(state.selectedList.length===0){return;}
    ElMessageBox.confirm(
        `一共有${state.selectedList.length}条数据,确认删除吗?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then((action) => {
            if(action === 'confirm'){
                let list = state.selectedList.map((item)=>{return item.projectId});
                deleteList({list:list},()=>{
                    onQuery();
                    ElMessage({
                        type: 'success',
                        message: '删除成功!',
                    });
                });
            }
        })
}

/**
 * 单个删除
 * @param row
 */
const deleteHandle = (row) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then((action) => {
            if(action === 'confirm'){
                deleteList({list:[row.projectId]},()=>{
                    onQuery();
                    ElMessage({
                        type: 'success',
                        message: '删除成功!',
                    });
                });
            }
        })
};

/**
 * 跳转方案管理
 * @param row
 */
const toProgrammeManagement = (row) => {
    router.push({path:`/investmentProjectManagement/preparatoryProject/reserveInvestmentProjectLibrary/programmeManagement/${row.projectId}`});
}

/**
 * 查看 --> 跳转详情
 * @param row
 */
const queryHandle = (row) => {
    router.push({path:`/investmentProjectManagement/preparatoryProject/reserveInvestmentProjectLibrary/details/${row.projectId}/${row.projectTypeId}/${row.projectApprovalStatus}`});
}

/**
 * 显示项目阶段弹窗
 */
const projectPhasePopupRef = ref(null);
const openProjectPhase = (row) => {
    projectPhasePopupRef.value.open(row);
}

/**
 * 打开立项审批单弹窗
 * @param row
 */
const projectApprovalFormRef = ref(null);
const openProjectApprovalForm = (row,type) => {
    projectApprovalFormRef.value.open(row,type);
}

/**
 * 打开立项议题弹窗
 * @param row
 */
const projectProposalRef = ref(null);
const openProjectProposal = (row,type) => {
    projectProposalRef.value.open(row,type);
}

onMounted(()=>{
    getData({
        pageNum:1,
        pageSize:10,
        param:{
            prepareStatus:-1
        }
    });
    getListEnum(1);
    getListEnum(2);
    getAllDepartments();
    getAllPartner();
    getCompanyList();
    getProjectSetPage({
        pageNum:1,
        pageSize:10000,
    });
});
</script>

<style lang="scss" scoped>
.interestCalculationDetailsPage{
  .delete-icon{
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
  .search-wrap{
    .search-item{

      .el-input{
        width: auto !important;
      }
    }
    .search-buttons{
      .icon-export{
        width: 18px;
        height: 18px;
      }
    }
  }
}
.public-dialog-content{
  .dialog-title-box{
    height: 30px;
    span{
      font-size: 15px;
      font-weight: 600;
    }
  }
}
</style>
